package sky.treasure;

import sky.treasure.properties.IProperty;
import sky.treasure.results.CannotMove;
import sky.treasure.results.EndOfAlgorithm;

/**
 * Created with IntelliJ IDEA.
 * User: Gauss
 * Date: 13.01.14
 * Time: 23:57
 * To change this template use File | Settings | File Templates.
 */
public class FindPathCoordinator implements ICoordinator {

    private Area area;
    private Coordinates destinationCoordinates;
    private Direction direction;

    public FindPathCoordinator(Area area, Coordinates destinationCoordinates) {
        this.area = area;
        this.destinationCoordinates = destinationCoordinates;
    }

    @Override
    public Cell getNextCell(Coordinates coordinates) {
        if (coordinates.equals(destinationCoordinates)) {
            Cell cell = new Cell(destinationCoordinates);
            cell.addProperty(new EndOfAlgorithm());
            return cell;
        }
        //only one sell obstacle
        Direction tempDir = Direction.calculateDirection(coordinates, destinationCoordinates);
        if (tempDir!=null && tempDir!=direction) {
            direction = tempDir;
        }
        Cell cell = tryThisDirection(coordinates, direction);
        if (cell!=null) {
            return cell;
        }
        cell = tryThisDirection(coordinates, direction.clockWise());
        if (cell!=null) {
            return cell;
        }
        cell = tryThisDirection(coordinates, direction.counterClockWise());
        return cell;
    }

    @Override
    public Cell getFirstCell() {
        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public Area getArea() {
        return area;
    }

    private boolean isCellApproval(Cell cell) {
        if (cell.isAbroad()) {
            return false;
        }
        if (cell.getProperties()==null) {
            return true;
        }
        for (IProperty property: cell.getProperties()) {
            if (property.analyzeCell(cell).getClass()== CannotMove.class) {
                return false;
            }
        }
        return true;
    }

    private Cell tryThisDirection(Coordinates coordinates, Direction direction) {
        Coordinates temp = new Coordinates(coordinates);
        direction.changeCoordinate(temp);
        Cell cell = area.getCell(temp);
        return isCellApproval(cell)?cell:null;
    }

}
